package com.example.project.config.shiro;

import com.alibaba.fastjson.JSONObject;
import com.example.project.base.ResultBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ShiroLoginFilter extends FormAuthenticationFilter {
    private static Logger logger = LoggerFactory.getLogger(ShiroLoginFilter.class);
    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向。
     * @param request
     * @param response
     * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        ResultBean resultBean = new ResultBean();
        resultBean.setCode(ResultBean.FAIL);
        resultBean.setMsg(new String("权限验证失败".getBytes(),"UTF-8"));

        logger.warn("权限验证失败");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.getWriter().write(JSONObject.toJSON(resultBean).toString());

//        if (isAjax(request)) {
//            httpServletResponse.setCharacterEncoding("UTF-8");
//            httpServletResponse.setContentType("application/json");
//            ResultData resultData = new ResultData();
//            resultData.setResult(1);
//            resultData.setCode(403);
//            resultData.setMessage("登录认证失效，请重新登录!");
//            httpServletResponse.getWriter().write(JSONObject.toJSON(resultData).toString());
//        }
//        else {
//            //saveRequestAndRedirectToLogin(request, response);
//            /**
//             * @Mark 非ajax请求重定向为登录页面
//             */
//            httpServletResponse.sendRedirect("/login");
//        }
        return false;
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }

        return super.isAccessAllowed(request, response, mappedValue);
    }

}